#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""
@file_name: multiprocess_the_fibonacci_sequence.py
@date: 2025-07-23 11:25
@author: Falling Snow
@desc: 多进程获取 Fibonacci 数据, 这个程序的复杂度有 O(2^n) 只作为测试.
"""
import multiprocessing
import os
import time


def print_fib(number: int) -> None:
    print(f"当前进程为: {os.getpid()}")

    def fib(n: int) -> int:
        if n == 1:
            return 0
        elif n == 2:
            return 1
        else:
            return fib(n - 1) + fib(n - 2)

    print(f"fib({number}) 结果为: {fib(number)}")


def fibs_multiprocess():
    """多线程获取fibonacci序列"""
    fortieth_process = multiprocessing.Process(target=print_fib, args=(40,))
    fortieth_process.start()
    forty_one_process = multiprocessing.Process(target=print_fib, args=(41,))
    forty_one_process.start()

    fortieth_process.join()
    forty_one_process.join()


if __name__ == '__main__':
    start = time.time()
    fibs_multiprocess()
    fibs_multiprocess()
    fibs_multiprocess()

    end = time.time()

    print(f"获取数据完成, 共耗费{((end - start) / 3):.4f} second")
